package team.zero.lemon.module.message.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import team.zero.lemon.common.date.UTC;
import team.zero.lemon.common.exception.CustomException;
import team.zero.lemon.common.persistence.Page;
import team.zero.lemon.common.security.session.SessionContext;
import team.zero.lemon.common.security.session.model.Session;
import team.zero.lemon.common.service.CrudService;
import team.zero.lemon.module.message.dao.IMessageActionDao;
import team.zero.lemon.module.message.dao.IMessageDao;
import team.zero.lemon.module.message.entity.Message;
import team.zero.lemon.module.message.entity.MessageAction;

import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * Created by fangpingxi on 2016/11/1.
 */
@Service
public class MessageService extends CrudService<IMessageDao, Message> {

    @Autowired
    MessageActionService messageActionService;

    @Transactional
    public int saveMessage(Message message) {
        try {
            Session session = SessionContext.getSession();
            if (session == null) {
                message.setUserId(0);
                message.setUserName("未知");
            } else {
                message.setUserId(session.getId());
                message.setUserName(session.getNikeName());
            }
            if (message.getStatus() == 1) {
                message.setSendTime(UTC.date());
            }
            int messageId = save(message);
            for (MessageAction messageAction : message.getMessageActions()) {
                if (messageAction.getId() != null) {
                    messageAction.setInsert(false);
                } else {
                    messageAction.setMessageId(messageId);
                }
                messageActionService.save(messageAction);
            }
            return messageId;
        } catch (Exception exc) {
            throw new CustomException(exc.getMessage());
        }
    }

    @Transactional
    public int deleteMessage(Message message) {
        try {
           return dao.deleteLogic(message);
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    public Page<Message> getDraftingPage(Message message) {
        try {
            message.page.setList(dao.getDraftingPage(message));
            return message.page;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    public Message getMessageById(Integer id) {
        try {
            Message message = dao.findById(id);
            message.setMessageActions(messageActionService.getMessageActionByMessageId(id));
            return message;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }
}
